#!/bin/bash



declare -a child_pids=()


# Function to monitor and handle process exit
monitor_process() {
    local pid=$1
    local name=$2
    local main_pid=$3

    # Monitor the process
    while true; do
        if ! kill -0 $pid 2>/dev/null; then
            echo "$name has exited"
            kill -s TERM $main_pid  # 发送终止信号给主进程
            break
        fi
        sleep 1
    done
}

# Kill all instances of udp2raw_amd64
killall udp2raw_amd64

# Start App 1
udp2raw_amd64 -c -l 0.0.0.0:55820 -r 192.168.60.23:13125 -k "password" --raw-mode faketcp -a &
app1_pid=$!
child_pids+=($app1_pid)

# Start monitoring App 1 in the background
monitor_process $app1_pid "App 1" $$ &  # $$ 获取当前进程的 PID，并传递给监控函数

# Store the PID of the monitor process
monitor_pid=$!

sleep 4

# Start App 2
udp2raw_amd64 -s -l 0.0.0.0:13126 -r 127.0.0.1:51820 -k "password" --raw-mode faketcp -a &
app2_pid=$!
child_pids+=($app2_pid)

# Start monitoring App 2 in the background
monitor_process $app2_pid "App 2" $$ &  # $$ 获取当前进程的 PID，并传递给监控函数

# Store the PID of the monitor process
monitor_pid2=$!

wg-quick up /opt/nvpc-standard-small/wg/wg0.conf

# 函数：在接收到TERM信号时，关闭所有子进程并退出
cleanup() {
    echo "Received TERM signal, killing all child processes..."
    for pid in "${child_pids[@]}"; do
        echo "Killing PID: $pid"
        kill -s TERM $pid >/dev/null 2>&1
    done
    exit 0
}

# 注册TERM信号的处理函数
trap cleanup TERM SIGINT SIGTERM


## Wait for Ctrl+C or termination signal
echo "Monitoring udp2raw_amd64 processes. Press Ctrl+C to exit."
wait
